<template>
  <!-- 系统管理-菜单管理 -->
  <div class="app-container">
    <el-row>
      <!-- 主机菜单列表 -->
      <el-col :span="12">
        <div class="operation-div">
          <h4>主机菜单列表（master）：
            <el-button type="primary" @click="saveMaster">保存更改</el-button>
          </h4>
        </div>
        <el-tree
            class="tree-content"
            :data="menuList"
            :draggable="true"
            default-expand-all
            node-key="id"
            :props="menuProps"
        >
          <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span>{{ node.label }}</span>
          <span>
            <a style="margin-left: 8px" @click="append(data)">
              <el-icon><Plus/></el-icon>
            </a>
            <a style="margin-left: 8px" @click="remove(node, data)"> <el-icon><Delete/></el-icon> </a>
          </span>
          <span style="margin-left: 16px">
            图标：
              <el-select
                  placeholder="选择图标"
                  size="small"
                  style="width: 90px"
                  @change="iconChange(data, $event)"
                  v-model="data.icon"
                  clearable
              >
                <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
          </span>
          <span style="margin-left: 8px">
            菜单地址
              <el-input size="small" style="width: 120px;" v-model="data.menuUrl"></el-input>
          </span>
        </span>
          </template>
        </el-tree>
      </el-col>
      <!-- 租户菜单列表 -->
      <el-col :span="12">
        <div class="operation-div">
          <h4>租户菜单列表（tenement）：
            <el-select @change="getTenementMenuList" placeholder="选择租户" v-model="selectedTenement"
                       style="width: 100px;margin-right: 20px">
              <el-option v-for="tenement in tenementList" :label="tenement.simpleName" :value="tenement.tenantKey"/>
            </el-select>
            <el-button type="info" @click="masterToTenement">同步菜单</el-button>
            <el-button type="primary" @click="saveTenement">保存更改</el-button>
          </h4>
        </div>
        <el-tree
            class="tree-content"
            :data="tenementMenuList"
            :draggable="true"
            default-expand-all
            node-key="id"
            :props="menuProps"
        >
          <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span>{{ node.label }}</span>
          <span>
            <a style="margin-left: 8px" @click="tenementAppend(data)">
              <el-icon><Plus/></el-icon>
            </a>
            <a style="margin-left: 8px" @click="tenementRemove(node, data)"> <el-icon><Delete/></el-icon> </a>
          </span>
          <span style="margin-left: 16px">
            图标：
              <el-select
                  placeholder="选择图标"
                  size="small"
                  style="width: 90px"
                  @change="tenementIconChange(data, $event)"
                  v-model="data.icon"
              >
                <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
          </span>
          <span style="margin-left: 8px">
            菜单地址
              <el-input size="small" style="width: 120px" v-model="data.menuUrl"></el-input>
          </span>
        </span>
          </template>
        </el-tree>
      </el-col>
    </el-row>

  </div>
</template>

<script setup>

import {onMounted, ref} from "vue";
import {getMenuListApi, getTenementMenuListApi, saveMenuApi} from "@/assets/api/system/menu";
import {Delete, Plus} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {getTenementListApi} from "@/assets/api/system/tenement";

// 记录id节点最大值
const countId = ref(0);
// 获取菜单列表
const menuList = ref([]);
const getList = () => {
  getMenuListApi().then(res => {
    menuList.value = res.data.data.list;
    countId.value = res.data.data.topId + 1;
  })
}

// 节点映射
const menuProps = {
  label: 'menuName',
  children: 'children'
}

// 保存菜单更改
const saveMaster = () => {
  const obj = {
    key: "master",
    list: menuList.value
  }
  const menuListJson = JSON.stringify(obj, null, 2);
  saveMenuApi(menuListJson).then(res => {
    if (res.data.code === 200) {
      ElMessage({
        type: 'success',
        message: `保存成功`,
      })
    }
  });
}

// 添加节点
const append = (data) => {
  // 菜单名称确认框
  ElMessageBox.prompt('请输入菜单名称', 'Tip', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    inputPattern:
        /([\u4e00-\u9fa5]|\w)+/,
    inputErrorMessage: '菜单名称',
  }).then(({value}) => {
    // 添加节点
    const newChild = {id: countId.value++, menuName: value, children: []}
    if (!data.children) {
      data.children = []
    }
    data.children.push(newChild)
    menuList.value = [...menuList.value]
    ElMessage({
      type: 'success',
      message: `添加成功`,
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '请输入中文字母数字',
    })
  })
}

// 删除节点
const remove = (node, data) => {
  const parent = node.parent
  const children = parent.data.children || parent.data
  const index = children.findIndex((d) => d.id === data.id)
  children.splice(index, 1)
  menuList.value = [...menuList.value]
}

// 菜单图标变更
const iconChange = (data, val) => {
  data.icon = val;
}

//-------------租户菜单-------------------
// 获取租户列表
const tenementList = ref([]);
const selectedTenement = ref('');
const getTenementList = () => {
  getTenementListApi().then(res => {
    tenementList.value = res.data.data;
  })
}

const tenementCountId = ref(0);
// 获取租户菜单列表
const tenementMenuList = ref([]);
const getTenementMenuList = () => {
  if (selectedTenement.value === null)
    return;
  getTenementMenuListApi(selectedTenement.value).then(res => {
    tenementMenuList.value = res.data.data.list;
    tenementCountId.value = res.data.data.topId + 1;
  })
}

// 添加节点
const tenementAppend = (data) => {
  // 菜单名称确认框
  ElMessageBox.prompt('请输入菜单名称', 'Tip', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    inputPattern:
        /([\u4e00-\u9fa5]|\w)+/,
    inputErrorMessage: '菜单名称',
  }).then(({value}) => {
    // 添加节点
    const newChild = {id: tenementCountId.value++, menuName: value, children: []}
    if (!data.children) {
      data.children = []
    }
    data.children.push(newChild)
    tenementMenuList.value = [...tenementMenuList.value]
    ElMessage({
      type: 'success',
      message: `添加成功`,
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '请输入中文字母数字',
    })
  })
}

// 删除节点
const tenementRemove = (node, data) => {
  const parent = node.parent
  const children = parent.data.children || parent.data
  const index = children.findIndex((d) => d.id === data.id)
  children.splice(index, 1)
  tenementMenuList.value = [...tenementMenuList.value]
}

// 菜单图标变更
const tenementIconChange = (data, val) => {
  data.icon = val;
}

// 同步租户菜单列表
const masterToTenement = () => {
  if (selectedTenement.value === '') {
    ElMessage({
      type: 'info',
      message: '请选择租户',
    })
    return;
  }
  // 同步菜单此处需要进行深拷贝
  tenementMenuList.value = JSON.parse(JSON.stringify(menuList.value));
  tenementCountId.value = countId.value;
  ElMessage({
    type: 'success',
    message: `同步成功`,
  })
}

// 保存租户菜单
const saveTenement = () => {
  if (selectedTenement.value === '') {
    ElMessage({
      type: 'info',
      message: '请选择租户',
    })
    return;
  }
  const obj = {
    key: selectedTenement.value,
    list: tenementMenuList.value
  }
  const menuListJson = JSON.stringify(obj, null, 2);
  saveMenuApi(menuListJson).then(res => {
    if (res.data.code === 200) {
      ElMessage({
        type: 'success',
        message: `保存成功`,
      })
    }
  });
}

onMounted(() => {
  getList();
  getTenementList();
});

// 菜单图标列表
const options = [
  {
    value: 'Setting',
    label: '设置',
  },
  {
    value: 'DataLine',
    label: '数据线',
  },
  {
    value: 'Notebook',
    label: '记事本',
  },
  {
    value: 'Message',
    label: '信息',
  },
  {
    value: 'DeleteFilled',
    label: '回收站',
  },
]
</script>

<style scoped>
.app-container {
  padding-left: 30px;
}

.tree-content {
  border: #bfbfbf 1px solid;
  border-radius: 5px;
  padding: 5px;
  max-width: 650px;
  background-color: #f8fff9;
  box-shadow: 2px 4px 8px 2px rgba(0, 0, 0, 0.2);
}
</style>